# coding = utf-8
from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response

from rest_framework.viewsets import ModelViewSet

from base.models import Unit, StoreHouse, Category, CustSuppClass, CustomSupplier, Goods, Company, Employee, \
    AccountTitle
from .serializers import UnitSerializer, StoreHouseSerializer, CategorySerializer, CustSuppClassSerializer, \
    CustomSupplierSerializer, GoodsSerializer, CompanySerializer, EmployeeSerializer, AccountTitleListSerializer, \
    AccountTitleSerializer


class UnitViewSet(ModelViewSet):
    """计量单位"""
    permission_classes = ()
    queryset = Unit.objects.all()
    serializer_class = UnitSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class StoreHouseViewSet(ModelViewSet):
    """仓库表"""
    permission_classes = ()
    queryset = StoreHouse.objects.all()
    serializer_class = StoreHouseSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name")

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class CategoryViewSet(ModelViewSet):
    permission_classes = ()
    pagination_class = None
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset


class CustSuppClassViewSet(ModelViewSet):
    """客商分类"""
    permission_classes = ()
    queryset = CustSuppClass.objects.all()
    serializer_class = CustSuppClassSerializer
    pagination_class = None

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset


class CustomerViewSet(ModelViewSet):
    """客户"""
    permission_classes = ()
    queryset = CustomSupplier.objects.filter(is_customer=1)
    serializer_class = CustomSupplierSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)
        parent_id = self.request.query_params.get("parent_id", None)
        cate_id = self.request.query_params.get("cate_id", None)
        linkman = self.request.query_params.get("linkman", None)
        telephone = self.request.query_params.get("telephone", None)

        if linkman:
            queryset = queryset.filter(linkman__contains=linkman)

        if telephone:
            queryset = queryset.filter(telephone__contains=telephone)

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(code__contains=name) | Q(help_code__contains=name))

        if parent_id:
            if parent_id != "-1":
                items = CustSuppClass.objects.filter(Q(path__contains=parent_id) | Q(id=int(parent_id))).values_list("id",                                                                                   flat=True)
                queryset = queryset.filter(cate_id__in=list(items))
        elif cate_id:
            queryset = queryset.filter(cate_id=int(cate_id))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data["is_customer"] = True
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class SupplierViewSet(ModelViewSet):
    """供应商"""
    permission_classes = ()
    queryset = CustomSupplier.objects.filter(is_supplier=1)
    serializer_class = CustomSupplierSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)
        code = self.request.query_params.get("code", None)
        cate_id = self.request.query_params.get("cate_id", None)
        linkman = self.request.query_params.get("linkman", None)
        telephone = self.request.query_params.get("telephone", None)
        help_code = self.request.query_params.get("help_code", None)
        parent_id = self.request.query_params.get("parent_id", None)

        if parent_id:
            if parent_id != "-1":
                items = CustSuppClass.objects.filter(Q(path__contains=parent_id) | Q(id=int(parent_id))).values_list("id", flat=True)
                queryset = queryset.filter(cate_id__in=list(items))
        elif cate_id:
            queryset = queryset.filter(cate_id=int(cate_id))

        if code:
            queryset = queryset.filter(code__contains=code)

        if linkman:
            queryset = queryset.filter(linkman__contains=linkman)

        if telephone:
            queryset = queryset.filter(telephone__contains=telephone)

        if name:
            queryset = queryset.filter(name__contains=name)

        if help_code:
            queryset = queryset.filter(help_code__contains=help_code)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data["is_supplier"] = True
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class GoodsViewSet(ModelViewSet):
    """商品管理"""
    permission_classes = ()
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        # code = self.request.query_params.get("code", None)
        name = self.request.query_params.get("name", None)
        parent_id = self.request.query_params.get("parent_id", None)
        cate_id = self.request.query_params.get("cate_id", None)
        # help_code = self.request.query_params.get("help_code", None)

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(code__contains=name) | Q(help_code__contains=name))

        if parent_id:
            if parent_id != "-1":
                items = Category.objects.filter(Q(path__contains=parent_id) | Q(id=int(parent_id))).values_list("id", flat=True)
                queryset = queryset.filter(cate_id__in=list(items))
        elif cate_id:
            queryset = queryset.filter(cate_id=int(cate_id))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class CompanyViewSet(ModelViewSet):
    """公司信息"""
    permission_classes = ()
    queryset = Company.objects.all()
    serializer_class = CompanySerializer
    pagination_class = None


class AccountTitleViewSet(ModelViewSet):
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = AccountTitle.objects.all()
    serializer_class = AccountTitleSerializer

    def get_queryset(self):
        queryset = super(AccountTitleViewSet, self).get_queryset()
        if self.lookup_field in self.kwargs:
            return queryset

        name = self.request.query_params.get("name")
        if name:
            queryset = queryset.filter(name__contains=name)
        else:
            queryset = queryset.filter(parent=None)

        return queryset

    def get_serializer_class(self):
        name = self.request.query_params.get("name")
        if name:
            return AccountTitleListSerializer

        return super(AccountTitleViewSet, self).get_serializer_class()


class EmployeeViewSet(ModelViewSet):
    # authentication_classes = ()
    permission_classes = ()
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name")
        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(telephone__contains=name))

        return queryset


class EmployeeListAPIView(ListAPIView):
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer
